package slave

import (
	"backend/internal/common/errorx"
	"backend/internal/db/model"
	"context"
	"fmt"
	"net/http"

	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddSlaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddSlaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddSlaveLogic {
	return &AddSlaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddSlaveLogic) AddSlave(req *types.Slave) (resp *types.BaseResponse, err error) {
	// 查询设备Id
	var device model.Device
	err = l.svcCtx.GormDB.Where("name = ?", req.DeviceName).First(&device).Error
	if err != nil {
		errorStr := fmt.Sprintf("设备 %v 不存在: ", req.DeviceName)
		logx.Errorf(errorStr)
		return nil, errorx.NewDefaultError(errorStr)
	}

	var slave model.Slave
	slave = model.Slave{
		DeviceID: device.ID,
		SlaveID:  int32(req.SlaveId),
	}
	err = l.svcCtx.GormDB.Create(&slave).Error
	if err != nil {
		errorStr := fmt.Sprintf("添加从站 %d 失败: %v", slave.SlaveID, err)
		logx.Errorf(errorStr)
		return nil, errorx.NewDefaultError(errorStr)
	}
	return &types.BaseResponse{
		Status: http.StatusOK,
		Msg:    fmt.Sprintf("添加从站 %d 成功!", slave.SlaveID),
		Data:   true,
	}, nil
}
